package com.jeecg.demo.api;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.core.util.oConvertUtils;
import org.jeecgframework.jwt.util.ResponseMessage;
import org.jeecgframework.jwt.util.Result;
import org.jeecgframework.web.system.service.SystemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.jeecg.demo.entity.AppInfoReviewEntity;
import com.jeecg.demo.entity.AppInformationEntity;
import com.jeecg.demo.service.AppAdInfoServiceI;
import com.jeecg.demo.service.AppInfoReviewServiceI;
import com.jeecg.demo.util.PropertiesUtil;
import com.jeecg.demo.util.TimerUtil;

@Api(value = "AppAdInfo", description = "客服咨询表", tags = "AppAdInfo")
@Controller
@RequestMapping("/app_infomation")
public class infomation {
    @Autowired
    private AppAdInfoServiceI appAdInfoServiceI;
    @Autowired
    private AppInfoReviewServiceI appInfoReviewServiceI;
    @Autowired
    private SystemService systemService;

    /**
     * 竞价预告
     */
    @RequestMapping(value = "/AnnountInfo", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "招标拍卖预告", produces = "application/json")
    ResponseMessage<List<Map<String, Object>>> AnnountInfoList(@RequestParam(required = false) String direction) {
        String sql = "";
        if (StringUtil.isEmpty(direction)) {
            return null;
        }
        sql = "select ANNOUNCEMENTID,ANNOUNTITLE,ANNOUNCONTENT,ANNOUNTYPE,POCODE,POID,ANNOUNTIME,ZHUANGT" +" from ANNOUNCEMENT order by annountime desc";

        /*
         * else { sql =
         * "select poid,pocode,potraderid,direction,poprice,potradername,validstartdate,validenddate,annountitle,pmygcontent "
         * + "from postorder where direction = ? and annountitle is not null"; }
         */

        List<Map<String, Object>> listMap = systemService.findForJdbc(sql);

        return Result.success(listMap);
    }

    /**
     * 竞价预告详情
     */
    @RequestMapping(value = "/AnnountInfoDetail", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "招标拍卖预告详情", produces = "application/json")
    ResponseMessage<List<Map<String, Object>>> AnnountInfoDetail(@RequestParam(required = false) String announcementid) {
        String sql = "";
        if (StringUtil.isEmpty(announcementid)) {
            return null;
        }

        sql = "select ANNOUNCEMENTID,ANNOUNTITLE,ANNOUNCONTENT,ANNOUNTYPE,POCODE,POID,ANNOUNTIME,ZHUANGT"
                + " FROM ANNOUNCEMENT where ANNOUNCEMENTID=? order by annountime desc";

        List<Map<String, Object>> listMap = systemService.findForJdbc(sql,
                announcementid);

        return Result.success(listMap);
    }

    /**
     * 竞价结果预告
     */
    @RequestMapping(value = "/AnnountResult", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "竞价结果预告列表", produces = "application/json")
    ResponseMessage<List<Map<String, Object>>> AnnountResult(
            @RequestParam(required = false) String nodeId) {
        String sql = "";
        if (StringUtil.isEmpty(nodeId)) {
            return null;
        }

        sql = "select * from v_cms_info_detail d where d.f_node_id=? order by d.f_publish_date desc";

        List<Map<String, Object>> listMap = systemService.findForJdbc(sql,
                nodeId);

        return Result.success(listMap);
    }

    /**
     * 竞价结果详情
     */
    @RequestMapping(value = "/AnnountResultDetail", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "竞价结果预告列表", produces = "application/json")
    ResponseMessage<List<Map<String, Object>>> AnnountResultDetail(
            @RequestParam(required = false) String infoId) {
        String sql = "";
        if (StringUtil.isEmpty(infoId)) {
            return null;
        }

        sql = "select * from v_cms_info_detail d where d.f_info_id=?";

        List<Map<String, Object>> listMap = systemService.findForJdbc(sql, infoId);

        return Result.success(listMap);
    }

    /**
     * 广告位轮播
     */
    @RequestMapping(value = "/AdManager", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "广告位轮播", produces = "application/json")
    public ResponseMessage<List<Map<String, Object>>> list(@RequestParam(required = false) String type // 广告位编号
    ) {
        if (StringUtil.isEmpty(type)) {
            return null;
        }
        String sql = "select i.* from app_ad_info i inner join app_ad_space s on i.adspace_id = s.adspace_id where i.sysid in (select max(i.sysid) from app_ad_info i "
                + " where i.status =1 and i.ad_area_id=?"
                + " group by i.adspace_id) order by s.ordernum asc";
        List<Map<String, Object>> listMap = systemService
                .findForJdbc(sql, type);
        return Result.success(listMap);
    }

    /**
     * 广告详情
     */
    @RequestMapping(value = "/getAdContent")
    @ResponseBody
    @ApiOperation(value = "广告详情", produces = "application/json")
    public ResponseMessage<List<Map<String, Object>>> AdContent(
            @RequestParam(required = false) String adInfoid // 信息编号
    ) {
        if (StringUtil.isEmpty(adInfoid)) {
            return null;
        }
        String sql = "select t.ad_info_id,t.title,t.create_date,a.content,t.source "
                + "from APP_AD_INFO t,app_ad_content a where t.ad_info_id=a.ad_info_id and t.ad_info_id=?";
        List<Map<String, Object>> listMap = systemService.findForJdbc(sql,
                adInfoid);
        return Result.success(listMap);
    }

    /**
     * 信息资讯列表
     * 
     * @param type
     * @param page
     * @return
     */
    @RequestMapping(value = "/getListXxData")
    @ResponseBody
    @ApiOperation(value = "信息资讯列表", produces = "application/json")
    public ResponseMessage<List<Map<String, Object>>> getZXListXx(
            @RequestParam(required = false) String nodeid, // 信息类型
            @RequestParam(required = false, defaultValue = "0") String begin, // 页数
            @RequestParam(required = false, defaultValue = "10") String end) {
        String sql;
        sql = "select * from (SELECT A.*, ROWNUM RN from ("
                + " SELECT * FROM V_APP_INFORMATION t WHERE t.INFO_TYPE_ID=? and t.STATUS=1 order by t.CREATE_DATE desc"
                + ") A WHERE ROWNUM <= ?) WHERE RN > ? ";
        List<Map<String, Object>> listMap = systemService.findForJdbc(sql,
                nodeid, end, begin);
        return Result.success(listMap);
    }

    /**
     * 信息资讯列表
     * 
     * @param type
     * @param page
     * @return
     */
    @RequestMapping(value = "/getListXxDetail")
    @ResponseBody
    @ApiOperation(value = "信息资讯列表", produces = "application/json")
    public ResponseMessage<List<Map<String, Object>>> getZXListXxDetail(
            @RequestParam(required = false) String infoid // 信息类型
    ) {
        String sql;
        sql = "SELECT * FROM V_APP_INFORMATION t WHERE t.info_id=?";
        List<Map<String, Object>> listMap = systemService.findForJdbc(sql,
                infoid);
        return Result.success(listMap);
    }

    /**
     * 信息咨询详情//衍生品详情
     * 
     * @param INFO_ID
     * @return
     */
    @RequestMapping(value = "/getZXContent")
    @ResponseBody
    @ApiOperation(value = "信息咨询详情", produces = "application/json")
    public ResponseMessage<List<Map<String, Object>>> zxContent(
            @RequestParam(required = false) String infoid // 信息编号
    ) {
        if (StringUtil.isEmpty(infoid)) {
            return null;
        }
        String sql = "select a.* ,b.*  from app_information a ,app_info_content b  "
                + "where a.info_id=b.info_id and  a.INFO_ID=?";
        List<Map<String, Object>> listMap = systemService.findForJdbc(sql,
                infoid);
        return Result.success(listMap);
    }

    /**
     * 取收藏数
     * 
     * @param infoid
     * @return
     */
    @RequestMapping(value = "/getCollectCount")
    @ResponseBody
    @ApiOperation(value = "去信息收藏数", produces = "application/json")
    public int collectCount(@RequestParam(required = false) String infoid // 信息编号
    ) {
        String sql = "select * from APP_USER_COLLECTION where INFO_ID=? and current_state ='1'";
        List<Map<String, Object>> collectCount = systemService.findForJdbc(sql,
                infoid);
        return collectCount.size();
    }

    /**
     * 增加阅读数
     * 
     * @param infoid
     * @return
     */
    @RequestMapping(value = "/addReadCount")
    @ResponseBody
    @ApiOperation(value = "阅读数", produces = "application/json")
    public ResponseMessage<?> readCount(
            @RequestParam(required = false) int infoid // 信息编号
    ) {
        int readCount = 0;
        AppInformationEntity appInfo = systemService.get(
                AppInformationEntity.class, infoid);
        if (oConvertUtils.isNotEmpty(appInfo)) {
            if (appInfo.getReadCount() != null) {
                readCount = appInfo.getReadCount();
            }
            appInfo.setReadCount(readCount + 1);
            appInfo.setUpdateDate(new Date());
        }
        try {
            systemService.saveOrUpdate(appInfo);
        }
        catch (Exception e) {
            return Result.error(e.getMessage());
        }
        return Result.success(appInfo);
    }

    /**
     * 添加评论
     * 
     * @param infoid
     * @param userid
     * @param reviewDesc
     */
    @RequestMapping(value = "/adreview")
    @ResponseBody
    @Transactional(isolation = Isolation.READ_COMMITTED, timeout = 5)
    @ApiOperation(value = "添加评论")
    public ResponseMessage<?> addadreview(
            @RequestParam(required = false) String userid, // 用户编号
            @RequestParam(required = false) String infoid, // 信息编号
            @RequestParam(required = false) String reviewDesc // 评论内容
    ) {
        if (StringUtil.isEmpty(userid + "")) {
            return Result.error("用户编号不能为空");
        }
        if (StringUtil.isEmpty(infoid)) {
            return null;
        }
        if (StringUtil.isEmpty(reviewDesc)) {
            return Result.error("请输入回复内容");
        }
        AppInfoReviewEntity appInfoReviewEntity = new AppInfoReviewEntity();
        try {
            appInfoReviewEntity.setSysid(Integer.parseInt(infoid));
            appInfoReviewEntity.setInfoId(Integer.parseInt(infoid));
            appInfoReviewEntity.setUserid(Integer.parseInt(userid));
            appInfoReviewEntity.setReviewDesc(reviewDesc);
            appInfoReviewEntity.setReviewTime(TimerUtil.getCurrentTimeStamp());
            appInfoReviewEntity.setIsvalid("1");
            appInfoReviewServiceI.save(appInfoReviewEntity);
        }
        catch (Exception e) {
            e.printStackTrace();
            return Result.error("失败");
        }
        return Result.success(appInfoReviewEntity);
    }
    
    /**
     * 评论列表
     * 
     * @param type
     * @param sysid
     * @param page
     */
    @RequestMapping(value = "/getCommentList",method= RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "评论列表",produces = "application/json")
    public ResponseMessage<List<Map<String, Object>>> getCommentList(
            @RequestParam(required = false, defaultValue = "1") String page, // 页数
            @RequestParam(required = false) String infoId // 信息编号
    ) {
        if (StringUtil.isEmpty(page)) {
            return null;
        }
        if (StringUtil.isEmpty(infoId)) {
            return null;
        }
        int begin = (Integer.parseInt(page) - 1) * 10;
        int end = 10 * Integer.parseInt(page);
        String sql = "select * from (SELECT A.*, ROWNUM RN from ( select t.*,u.headpic_path,s.username from APP_INFO_REVIEW t left join app_user_headpic u   on  u.userid=t.userid left join SYS_USER s on  s.userid=t.userid and s.userid=t.userid  where t.info_id=? and t.isvalid=1 order by t.review_time desc ) A WHERE ROWNUM <= ?) WHERE RN > ?";
        List<Map<String, Object>> listMap = systemService.findForJdbc(sql,
              infoId, end, begin);
        return Result.success(listMap);
    }
    /**
     * 取专题
     * 
     * @param type
     * @param sysid
     * @param page
     */
    @RequestMapping(value = "/getSubList")
    @ResponseBody
    @ApiOperation(value = "取专题列表")
    public ResponseMessage<List<Map<String, Object>>> subList(
            @RequestParam(required = false) String type, // 信息类型
            @RequestParam(required = false, defaultValue = "10") String page, // 页数
            @RequestParam(required = false) String sysid // 信息编号
    ) {
        if (StringUtil.isEmpty(type)) {
            return null;
        }
        if (StringUtil.isEmpty(page)) {
            return null;
        }
        if (StringUtil.isEmpty(sysid)) {
            return null;
        }
        int begin = (Integer.parseInt(page) - 1) * 10;
        int end = 10 * Integer.parseInt(page);
        String sql = "select * from (SELECT A.*, ROWNUM RN from (select *  from app_information where info_type_id= ? and STATUS=1 and  set_top in(0,1) and subject_code=?   order by create_date desc) A WHERE ROWNUM <= ?) WHERE RN > ?";
        List<Map<String, Object>> listMap = systemService.findForJdbc(sql,
                type, sysid, end, begin);
        return Result.success(listMap);
    }

    /**
     * 热点头条
     */
    @RequestMapping(value = "/getNaviPicList")
    @ResponseBody
    @ApiOperation(value = "头条图片")
    public ResponseMessage<List<Map<String, Object>>> MenuPic() {
        String sql = "select * from APP_NAVI_PIC t";
        List<Map<String, Object>> listMap = systemService.findForJdbc(sql);
        return Result.success(listMap);
    }

    /**
     * 价格指数 历史查询
     */
    @RequestMapping(value = "/getPriceindexList")
    @ResponseBody
    @ApiOperation(value = "历史查询")
    public ResponseMessage<List<Map<String, Object>>> PriceindexList(
            @RequestParam(required = false, defaultValue = "10") int pageSize, // 每页行数
            @RequestParam(required = false, defaultValue = "1") int curPage // 当前页码
    ) {
        String sql = "select * from app_information where info_type_id = 7 and STATUS = 1 and title like '中国太原煤炭交易价格指数%' order by create_date desc";
        List<Map<String, Object>> listMap = systemService.findForJdbcParam(sql,
                curPage, pageSize);
        return Result.success(listMap);
    }

    /**
     * 衍生品列表
     */
    @RequestMapping(value = "/getDerivateList")
    @ResponseBody
    @ApiOperation(value = "衍生品列表")
    public ResponseMessage<List<Map<String, Object>>> DerivateList(
            @RequestParam(required = false) String type, // 信息类型
            @RequestParam(required = false, defaultValue = "10") int pageSize, // 每页行数
            @RequestParam(required = false, defaultValue = "1") int curPage // 当前页码
    ) {
        String sql = "select * from app_information where  info_type_id=? and STATUS=1 order by create_date desc";
        List<Map<String, Object>> listMap = systemService.findForJdbcParam(sql,
                curPage, pageSize, type);
        return Result.success(listMap);
    }

    /**
     * 分享信息详情
     */
    @RequestMapping(value = "/ShareContent")
    @ResponseBody
    @ApiOperation(value = " 分享信息")
    public ModelAndView ShareContent(@RequestParam(required = false) String id,
            HttpServletRequest req) {
        ResponseMessage<List<Map<String, Object>>> appInfo = zxContent(id);
        req.setAttribute("info", appInfo.getData().get(0));
        String conent = (String) appInfo.getData().get(0).get("CONTENT");
        req.setAttribute("content", checkAndUpdate(conent));
        return new ModelAndView("com/jeecg/ctctc/content");
    }

    /**
     * 物流介绍详情
     */
    @RequestMapping(value = "/LogisticsDetails")
    @ResponseBody
    @ApiOperation(value = " 物流介绍信息")
    public ResponseMessage<List<Map<String, Object>>> LogisticsDetails(
            @RequestParam(required = false) String aboutId) {
        String sql = "select * from APP_ABOUT where about_id = ? ";
        List<Map<String, Object>> listMap = systemService.findForJdbc(sql,
                aboutId);
        return Result.success(listMap);
    }

    /**
     * 轮播分享信息详情
     */
    @RequestMapping(value = "/ShareAdContent")
    @ResponseBody
    @ApiOperation(value = " 轮播分享信息")
    public ModelAndView ShareAdContent(
            @RequestParam(required = false) String id, HttpServletRequest req) {
        ResponseMessage<List<Map<String, Object>>> appAdInfo = AdContent(id);
        req.setAttribute("adInfo", appAdInfo.getData().get(0));
        String conent = (String) appAdInfo.getData().get(0).get("CONTENT");
        req.setAttribute("adContent", checkAndUpdate(conent));
        return new ModelAndView("com/jeecg/ctctc/Ad_content");
    }

    public static String checkAndUpdate(String str) {

        String url = "";
        String head = PropertiesUtil.getPropertiesValue("syspath");

        if (str != null) {
            str = str.replaceAll("font-size:16px;", "font-size:1.2em;");
            String[] result = str.split("<img");
            url = result[0];
            for (int i = 1; i < result.length; i++) {
                StringBuffer sb = new StringBuffer("<img" + result[i]);

                if (sb.indexOf("http", 1) < 0
                        || sb.indexOf("http") > sb.indexOf("src=") + 1) {// 不存在http
                    int startAt = sb.indexOf("src", 1) + 5;
                    int dirStartAt = sb.indexOf("/upload", 1);
                    if (dirStartAt > 0) {
                        sb.replace(startAt, dirStartAt + 7, "");
                    }

                    // StringBuffer sb2 = sb.insert(startAt, head);
                    int dirStartAt2 = sb.indexOf("/UploadFile/", 1);
                    if (dirStartAt2 > 0) {
                        sb.replace(startAt, dirStartAt2 + 12, "");
                    }
                    int dirStartAt3 = sb.indexOf("UploadFile//", 1);
                    if (dirStartAt3 > 0) {
                        sb.replace(startAt, dirStartAt3 + 12, "");
                    }

                    StringBuffer sb3 = sb.insert(startAt, head);
                    url = url + sb3.toString();

                }
                else {// 存在
                    url = url + sb.toString();
                    continue;
                }
            }
        }

        // System.out.println(url);
        return url + "<style>img{width:100%;}</style>";
    }
}
